/**
 * 
 */
package com.gr.staffpm.pages.management.resources.team;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wicketstuff.annotation.mount.MountPath;
import org.wicketstuff.annotation.strategy.MountHybrid;

import com.gr.staffpm.StaffPMWebPage;
import com.gr.staffpm.datatypes.Group;
import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.dhtmlx.DHTMLScope;
import com.gr.staffpm.dhtmlx.datatypes.Project;
import com.gr.staffpm.dhtmlx.datatypes.Task;
import com.gr.staffpm.security.service.UserService;
import com.gr.staffpm.tasks.service.TaskService;


/**
 * @author Graham Rhodes 20 Jan 2011 19:53:12
 */
@MountHybrid
@MountPath(path = "secure/management/TeamResources")
public class TeamResourcesPage extends StaffPMWebPage implements IHeaderContributor {

    @SpringBean(name = "taskService")
    private TaskService taskService;
    @SpringBean(name = "userService")
    private UserService userService;
    private final Logger log = LoggerFactory.getLogger(getClass());
    private final List<Project> projects = new ArrayList<Project>();

    public TeamResourcesPage(PageParameters parameters) {

        User currentUser = userService.getCurrentUser();
        List<User> usersInGroup = new ArrayList<User>();
        for (Group group : currentUser.getGroups())
            usersInGroup.addAll(userService.getUsersInGroupByGroupName(group.getName(), currentUser, userService.getUsersHighestLevel(currentUser)));

        for (User user : usersInGroup) {
            List<com.gr.staffpm.datatypes.Task> userTasks = taskService.getUserTasks(user);
            log.debug("User: " + user.getUsername() + " has " + userTasks.size() + " assigned tasks.");
            Project currentProject = new Project();
            currentProject.setId(user.getUserId());
            currentProject.setName(user.getFullName());

            //TODO get projects user is working on
            for (com.gr.staffpm.datatypes.Task task : userTasks) {
                Task currentTask = new Task();
                currentTask.setId(task.getTaskId());
                currentTask.setName(task.getName());
                currentTask.setEst(task.getCreated());
                DateTime start = new DateTime(task.getCreated());
                DateTime end = new DateTime(task.getDueDate());
                Duration duration = new Duration(start, end);
                long durationInHours = (((duration.getMillis() / 1000) / 60) / 60);
                currentTask.setDuration(durationInHours);
                currentTask.setPercentcompleted(100);
                currentProject.addTask(currentTask);
            }
            if (currentProject.getTasks().size() > 0)
                currentProject.setStartdate(findEarliestTask(currentProject.getTasks()));
            projects.add(currentProject);
        }

    }

    private Date findEarliestTask(List<Task> tasks) {
        Date earliestTask = Calendar.getInstance().getTime();
        for (Task task : tasks) {
            if (task.getEstAsDate().compareTo(earliestTask) < 0)
                earliestTask = task.getEstAsDate();
        }
        return earliestTask;
    }

    /* (non-Javadoc)
     * @see com.gr.staffpm.StaffPMWebPage#getTitle()
     */
    @Override
    public String getTitle() {
        return "Team Resources - StaffPM";
    }

    /* (non-Javadoc)
     * @see org.apache.wicket.markup.html.IHeaderContributor#renderHead(org.apache.wicket.markup.html.IHeaderResponse)
     */
    @Override
    public void renderHead(IHeaderResponse response) {
        response.renderCSSReference(new ResourceReference(DHTMLScope.class, "dhtmlxgantt.css"));
        response.renderJavascriptReference(new ResourceReference(DHTMLScope.class, "dhtmlxcommon.js"));
        response.renderJavascriptReference(new ResourceReference(DHTMLScope.class, "dhtmlxgantt.js"));
    }

    /* (non-Javadoc)
     * @see com.gr.staffpm.StaffPMWebPage#onBeforeRender()
     */
    @Override
    protected void onBeforeRender() {

        final String xml = TeamResourcesXMLSerializer.toXMLString(projects);
        Label script = new Label("ganttChartScript", new Model<String>()) {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                StringBuffer sb = new StringBuffer();
                sb.append("var gantt = new GanttChart(); gantt.setImagePath('");
                sb.append(urlFor(new ResourceReference(DHTMLScope.class, "imgs/")));
                sb.append("'); gantt.setEditable(false); gantt.create('resourcesChart'); gantt.loadData('" + xml + "',false,true);");
                replaceComponentTagBody(markupStream, openTag, sb.toString());
            }
        };
        addOrReplace(script);
        super.onBeforeRender();
    }

}
